<?php
set_include_path($_SERVER ['DOCUMENT_ROOT']);
include_once 'admin/includes/functions/admin-functions.php';
include_once 'admin/includes/functions/dashboard-functions.php';
global $DBobject, $SMARTY, $CONFIG;

if (empty($_SESSION['user']['admin'])) {
    header("location: /admin/login");
    die();
}

$general = array();

$franchiseeIdArr = $_SESSION['user']['admin']['franchisee'];

$termssql = "SELECT DISTINCT(termcategory_id),termcategory_name,DATE_FORMAT(term_start_date,'%Y') AS year,term_start_date FROM tbl_term LEFT JOIN tbl_termcategory ON term_termcategory_id = termcategory_id WHERE term_deleted IS NULL AND term_published = 1 ORDER BY term_start_date DESC";
if ($termres = $DBobject->wrappedSql($termssql)) {
    $SMARTY->assign("termgroups", $termres);
}

// Load current term category ID
$tsql = "SELECT term_object_id, term_termcategory_id,DATE_FORMAT(term_start_date,'%Y') AS year FROM tbl_term WHERE term_deleted IS NULL AND term_published = 1 AND term_start_date <= NOW() ORDER BY term_start_date DESC LIMIT 1";
$res = $DBobject->wrappedSql($tsql);
foreach ($termres as $tr) {
    if ($tr['termcategory_id'] == $res[0]['term_termcategory_id']) {
        $SMARTY->assign("currentterm", $tr['termcategory_name']);
    }
}

$current_term = $res[0]['term_termcategory_id'];
$current_year = $res[0]['year'];

if (!empty($_REQUEST['year'])) {
    $current_year = $_REQUEST['year'];
}
if (!empty($_REQUEST['term'])) {
    $current_term = $_REQUEST['term'];
}
$SMARTY->assign('sel_year', $current_year);
$SMARTY->assign('sel_term_id', $current_term);

if (!empty($current_term) && !empty($current_year)) {
    $sqlyear = "SELECT term_termcategory_id, DATE_FORMAT(term_start_date,'%Y') AS year FROM tbl_term WHERE term_termcategory_id != :term AND term_start_date <= NOW() AND term_start_date < (SELECT MIN(tm.term_start_date) FROM tbl_term AS tm WHERE tm.term_termcategory_id = :term AND DATE_FORMAT(tm.term_start_date,'%Y')=:year ) ORDER BY DATE_FORMAT(term_start_date,'%Y%m%d') DESC LIMIT 1";
    $pretmres = $DBobject->wrappedSql($sqlyear, array("term"=>$current_term,"year"=>$current_year));
    $pre_term = $pretmres[0]['term_termcategory_id'];
    $pre_year = $pretmres[0]['year'];

    //This section holds the Enrolment Status chart data
    $approved = enrolments(array("S", "MV"), null, null, array(1,2,3,4,5), $current_term, $current_year, $franchiseeIdArr);
    $trial = enrolments(array("T"), null, null, array(1,2,3,4,5), $current_term, $current_year, $franchiseeIdArr);
    $pending = enrolments(array("S", "MV"), null, null, array(7,8), $current_term, $current_year, $franchiseeIdArr);
    
    $pre_approved = enrolments(array("S", "MV"), null, null, array(1,2,3,4,5), $pre_term, $pre_year, $franchiseeIdArr);
    $pre_trial = enrolments(array("T"), null, null, array(1,2,3,4,5), $pre_term, $pre_year, $franchiseeIdArr);
    $pre_pending = enrolments(array("S", "MV"), null, null, array(7,8), $pre_term, $pre_year, $franchiseeIdArr);
    
    $general[] = array("label"=>"Enrolments","value"=>number_format($approved+$trial+$pending),"value2"=>number_format($pre_approved+$pre_trial+$pre_pending));
    
    $general[] = array("label"=>"Paid enrolments","value"=>number_format($approved),"value2"=>number_format($pre_approved));
    
    $revenue = revenue(null, null, null, array(1,2,3,4,5,12), $current_term, $current_year, $franchiseeIdArr);
    
    $pre_revenue = revenue(null, null, null, array(1,2,3,4,5,12), $pre_term, $pre_year, $franchiseeIdArr);
    setlocale(LC_ALL, array('en_AU.utf8', 'en_AU'));
    $general[] = array("label"=>"Revenue","value"=>money_format('%.2n', $revenue),"value2"=>money_format('%.2n', $pre_revenue));

    $general[] = array("label"=>"Pending enrolments","value"=>$pending,"value2"=>$pre_pending);
    $general[] = array("label"=>"Trial enrolments","value"=>$trial,"value2"=>$pre_trial);
    
    //$enrol = enrolments(array("S", "MV"),null,null,null,$current_term,$current_year);
    $redata = reenrolments(null, null, array(1,2,3,4,5,12), $current_term, $current_year, $franchiseeIdArr);
    $pre_redata = reenrolments(null, null, array(1,2,3,4,5,12), $pre_term, $pre_year, $franchiseeIdArr);
    $repercent = number_format(($redata['reenrolled']/$redata['previous'])*100, 2)."%";
    $pre_repercent = number_format(($pre_redata['reenrolled']/$pre_redata['previous'])*100, 2)."%";
    $general[] = array("label"=>"Re-enrolments","value"=>number_format($redata['reenrolled']),"value2"=>number_format($pre_redata['reenrolled']));
    $general[] = array("label"=>"Re-enrolments(%)","value"=>$repercent,"value2"=>$pre_repercent);
    
    $trials = trials(null, null, null, $current_term, $current_year, $franchiseeIdArr, true);
    $pre_trials = trials(null, null, null, $pre_term, $pre_year, $franchiseeIdArr, true);
    if (!empty($trials)) {
        $trialconverts = trialconversions(null, null, null, $current_term, $current_year, $franchiseeIdArr);
    } else {
        $trialconverts = 0;
    }
    
    if (!empty($pre_trials)) {
        $pre_trialconverts = trialconversions(null, null, null, $pre_term, $pre_year, $franchiseeIdArr);
    } else {
        $pre_trialconverts = 0;
    }
    $general[] = array("label"=>"Trial conversion (%)","value"=>(!empty($trials)?number_format(($trialconverts/$trials)*100, 2):number_format(0, 2))."%","value2"=>(!empty($pre_trials)?number_format(($pre_trialconverts/$pre_trials)*100, 2):number_format(0, 2))."%");
    
    $locations = locations($franchiseeIdArr);
    $general[] = array("label"=>"Locations","value"=>number_format($locations));
    $classdata = classes($current_term, $current_year, $franchiseeIdArr);
    $pre_classdata = classes($pre_term, $pre_year, $franchiseeIdArr);
    $general[] = array("label"=>"Classes","value"=>number_format($classdata['classes']),"value2"=>number_format($pre_classdata['classes']));
    $general[] = array("label"=>"Maximum capacity","value"=>number_format($classdata['maxsize'], 2),"value2"=>number_format($pre_classdata['maxsize'], 0));
    $general[] = array("label"=>"Enrolment rate","value"=>number_format(($approved+$trial+$pending)*100/intval($classdata['maxsize']), 2)."%","value2"=>number_format(($pre_approved+$pre_trial+$pre_pending)*100/intval($pre_classdata['maxsize']), 2)."%");
    //COMMENTED OUT - REQUEST BY CLIENT - 2015-05-22
    $general[] = array("label"=>"Average capacity","value"=>number_format($classdata['avgsize'], 2),"value2"=>number_format($pre_classdata['avgsize'], 2));
    

    $target = franchiseetarget($franchiseeIdArr);
    $percenttarget = number_format(($approved/$target)*100, 2);

    
    // //This section holds the Enrolment Status chart data
    $approved = enrolments(array("S", "MV"), null, null, array(1,2,3,4,5,12), $current_term, $current_year, $franchiseeIdArr);
    $trial = enrolments(array("T"), null, null, array(1,2,3,4,5,12), $current_term, $current_year, $franchiseeIdArr);
    $pending = enrolments(array("S", "MV"), null, null, array(7,8), $current_term, $current_year, $franchiseeIdArr);
    $enrolment = array(array("label"=>"Paid","value"=>$approved),array("label"=>"Trial","value"=>$trial),array("label"=>"Pending","value"=>$pending));

    
    $enrolmentsStateTerm= array();
    $year = $current_year;
    $term = $current_term;
    $termD = enrolmentbylocations(array("S", "MV"), array(1,2,3,4,5,12), $term, $year, $franchiseeIdArr);
    $sumD = 0;
    $termDStates = array();
    foreach ($termD as $t) {
        $termDStates[$t['location_name']] = $t;
        $sumD = $sumD + $t['enrolment'];
    }
    $key1 = "Term {$term}";

    
    $term = $term-1;
    if ($term <= 0) {
        $term = 4;
        $year = $year-1;
    }
    
    $termC = enrolmentbylocations(array("S", "MV"), array(1,2,3,4,5,12), $term, $year, $franchiseeIdArr);
    $sumC = 0;
    $termCStates = array();
    foreach ($termC as $t) {
        $termCStates[$t['location_name']] = $t;
        $sumC = $sumC + $t['enrolment'];
    }
    $key2 = "Term {$term}";
    
    
    $term = $term-1;
    if ($term <= 0) {
        $term = 4;
        $year = $year-1;
    }
    
    $termB = enrolmentbylocations(array("S", "MV"), array(1,2,3,4,5,12), $term, $year, $franchiseeIdArr);
    $sumB = 0;
    $termBStates = array();
    foreach ($termB as $t) {
        $termBStates[$t['location_name']] = $t;
        $sumB = $sumB + $t['enrolment'];
    }
    $key3 = "Term {$term}";
    
    
    $term = $term-1;
    if ($term <= 0) {
        $term = 4;
        $year = $year-1;
    }
    
    $termA = enrolmentbylocations(array("S", "MV"), array(1,2,3,4,5,12), $term, $year, $franchiseeIdArr);
    $sumA = 0;
    $termAStates = array();
    foreach ($termA as $t) {
        $termAStates[$t['location_name']] = $t;
        $sumA = $sumA + $t['enrolment'];
    }
    $key4 = "Term {$term}";
    
    $term = $term-1;
    if ($term <= 0) {
        $term = 4;
        $year = $year-1;
    }
    
    $params = array();
    if (!empty($franchiseeIdArr)) {
        $n=1;
        $tmpsql=array();
        foreach ($franchiseeIdArr as $m) {
            $tmpsql[] ="location_franchisee_id = :franchisee{$n}";
            $params[":franchisee{$n}"] = $m;
            $n++;
        }
    
        $sql_franchisee = " AND (".implode(" OR ", $tmpsql).")";
    }
    
    $sql = "SELECT DISTINCT(location_name) FROM tbl_location WHERE tbl_location.location_deleted IS NULL AND location_published = 1 {$sql_franchisee}";
    $resstate = $DBobject->wrappedSql($sql, $params);
    foreach ($resstate as $rs) {
        if (!array_key_exists($rs['location_name'], $termDStates)) {
            $termDStates[$rs['location_name']] = array("location_name"=>$rs['location_name'],"enrolment"=>0);
        }
        if (!array_key_exists($rs['location_name'], $termCStates)) {
            $termCStates[$rs['location_name']] = array("location_name"=>$rs['location_name'],"enrolment"=>0);
        }
        if (!array_key_exists($rs['location_name'], $termBStates)) {
            $termBStates[$rs['location_name']] = array("location_name"=>$rs['location_name'],"enrolment"=>0);
        }
        if (!array_key_exists($rs['location_name'], $termAStates)) {
            $termAStates[$rs['location_name']] = array("location_name"=>$rs['location_name'],"enrolment"=>0);
        }
    }
    
    ksort($termDStates);
    ksort($termCStates);
    ksort($termBStates);
    ksort($termAStates);
    
// 	// $termDStates['Total'] = array('enrolment'=>$sumD,"location_name"=>"Total");
// 	// $termCStates['Total'] = array('enrolment'=>$sumC,"location_name"=>"Total");
// 	// $termBStates['Total'] = array('enrolment'=>$sumB,"location_name"=>"Total");
// 	// $termAStates['Total'] = array('enrolment'=>$sumA,"location_name"=>"Total");
    
    
    $enrolmentsStateTerm["{$key1}"] = $termDStates;
    $enrolmentsStateTerm["{$key2}"] = $termCStates;
    $enrolmentsStateTerm["{$key3}"] = $termBStates;
    $enrolmentsStateTerm["{$key4}"] = $termAStates;
    $enrolmentsStateTerm =array_reverse($enrolmentsStateTerm, true);
    
    $colours = array("#48ac29","#009bdb","#f55d0f","#ffae00","#0bd0cd","#d6165e","#008081","#3a6475","#9b53d2","#ffdf06");
    $i=0;
    foreach ($enrolment as &$val) {
        $val['colourid'] = $i;
        $val['colour'] = $colours[$i];
        $i++;
    }
// 	$i=0;
// 	foreach($enrolmentsStateTerm as &$val){
// 	  $val['colour'] = $colours[$i];
// 	  $i++;
// 	} 
    $SMARTY->assign("enrolmentstatetermchartdata", $enrolmentsStateTerm);
    $SMARTY->assign("enrolmentstatetermfirstkey", key($enrolmentsStateTerm));
    $SMARTY->assign("enrolmentpiechartdata", $enrolment);
    $SMARTY->assign("generaldata", $general);
    $SMARTY->assign("target", $target);
    $SMARTY->assign("percenttarget", $percenttarget);
    $SMARTY->assign("enrolled", $approved);
}
